<template>
    <div class="exchange-container">
        <van-sticky>
            <div class="head">
                <img class="head-back-img" @click="goBack" src="../assets/back.svg" alt="">
                <div class="title">兑换详情</div>
            </div>
        </van-sticky>
        <!-- 商品展示区 - 优化布局 -->
        <div class="product-header">
            <div class="product-image-wrapper">
                <img :src="imgs" alt="商品图片" class="product-image">
                <div class="price-badge">
                    ¥{{ showPrice }}
                </div>
            </div>
            <div class="product-info">
                <h1 class="product-title">{{ info.product_name }}</h1>
                <div class="product-tag" v-if="info.tag">
                    <span>{{ info.tag }}</span>
                </div>
            </div>
        </div>
        <!-- 充值号码 -->
        <div class="recharge-section">
            <div class="recharge-title">充值号码</div>
            <van-field v-model="phonenumbers" placeholder="请输入11位手机号码" type="tel" maxlength="11" clearable
                class="recharge-input" @input="validatePhone" />
            <div class="error-tip" v-if="phoneError">{{ phoneError }}</div>
        </div>
        <!-- 兑换方式选择 -->
        <van-divider :style="{ color: '#ee473b', borderColor: '#ee473b', padding: '0 10px' }">
            <van-icon color="#ee473b" /> 选择兑换方式
        </van-divider>
        <div class="payment-cards">
            <div v-for="(item, index) in cardList" :key="index">
                <!-- 观影卡 -->
                <div class="card-item disabled-card" v-if="item.cardMode == 1">
                    <div class="disabled-tag">不能兑换福利</div>
                    <div class="card-content">
                        <van-icon name="coupon-o" size="24" class="card-icon movie-card" />
                        <div class="card-details">
                            <div class="card-number">卡号：{{ item.cardNo }}</div>
                            <div class="card-title">
                                <span>职工观影兑换卡</span>
                                <span class="card-balance">剩余{{ item.balance }}次</span>
                            </div>
                            <div class="card-expiry">
                                <span>有效期至 {{ item.validEndDate }}</span>
                            </div>
                        </div>
                    </div>
                    <van-checkbox :value="false" disabled checked-color="#ee473b" />
                </div>

                <!-- 积分卡 -->
                <div class="card-item" v-if="item.cardMode == 2" @click="selectPayment('points', item.cardMode, item)">
                    <div class="card-content">
                        <van-icon name="points" size="24" class="card-icon points-card" />
                        <div class="card-details">
                            <div class="card-number">卡号：{{ item.cardNo }}</div>
                            <div class="card-title">
                                <span>积分兑换</span>
                                <span class="card-balance">剩余{{ item.balance }}积分</span>
                            </div>
                            <div class="card-expiry">
                                <span>有效期至 {{ item.validEndDate }}</span>
                            </div>
                        </div>
                    </div>
                    <van-checkbox :value="isCardSelected(item.id)" checked-color="#ee473b" />
                </div>
            </div>
        </div>

        <!-- 使用说明 -->
        <van-divider :style="{ color: '#ee473b', borderColor: '#ee473b', padding: '0 10px' }">
            <van-icon color="#ee473b" /> 使用说明
        </van-divider>
        <div class="use-explain" v-html="info.use_explain"></div>

        <!-- 兑换按钮 -->
        <div class="exchange-footer">
            <van-button round block type="primary" class="exchange-btn" @click="handleExchange">
                确认兑换
            </van-button>
        </div>

        <!-- 价格明细弹窗 -->
        <van-popup round v-model="show" position="bottom">
            <div class="dialog_data">
                <div class="title">
                    <span>价格明细</span>
                </div>
                <div v-for="(item, index) in seatDeductions" :key="index" class="detailList">
                    <div>
                        <div class="flex_data">
                            <div>商品名称：</div>
                            <div>{{ item.product_name }}</div>
                        </div>
                    </div>
                    <div>
                        <div class="flex_data flex_data-money" style="margin-top: 8px;">
                            <div>原价：</div>
                            <div>
                                <span>{{ item.seatPrice }}</span>
                            </div>

                        </div>
                        <div style="margin-top: 8px;" class="flex_data flex_data-money">
                            <div>抵扣的金额 ：</div>
                            <div>
                                <span>{{ item.deduction || 0 }}</span>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="flex_data">
                            <div>实际支付：</div>
                            <div>{{ totalPay || 0 }}</div>
                        </div>
                    </div>
                </div>
                <div class="flex-btn">
                    <!-- <div @click="goPay">
                        去支付
                    </div> -->
                    <div class="pay-btn" :class="{ loading: paymentLoading }" @click="goPay">
                        <van-loading v-if="paymentLoading" type="spinner" size="20px" />
                        <span v-else>去支付</span>
                    </div>
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { Toast } from 'vant';
import wechatPay from '@/utils/wechatPay';
import plantAPI from "@/api/plant";

export default {
    data() {
        return {
            paymentLoading: false,
            paymentLock: false,
            isPaying: false,
            phoneError: '',
            phonenumbers: '',
            imgs: '',
            show: false,
            seatDeductions: [],
            totalPay: '',
            selectedCardMode: null,
            selectedCards: [],
            productNo: '',
            info: {},
            cardList: [],
            hasEnoughPointsCard: false,
            showPrice:0,
        }
    },
    created() {
        const data = JSON.parse(sessionStorage.getItem('welfarePayData') || '{}');
        // 赋值到对应字段
        this.productNo = data.productNo || '';
        this.imgs = data.imgs || '';
        this.phonenumbers = data.rechargeNumber || '';
         this.showPrice = data.showPrice || 0;
        sessionStorage.removeItem('welfarePayData');
        plantAPI.conversionDetail(this.productNo).then(res => {
            this.info = res.data
        })
        plantAPI.cardList().then(res => {
            this.cardList = res.rows
        })
    },
    methods: {
        goBack() {
            this.$router.push({
                path: '/welfare'
            })
        },
        validatePhone() {
            const phone = this.phonenumbers.trim();
            if (!phone) {
                this.phoneError = '请输入手机号码';
                return false;
            }
            if (!/^1[3-9]\d{9}$/.test(phone)) {
                this.phoneError = '请输入正确的手机号码';
                return false;
            }
            this.phoneError = '';
            return true;
        },
        formatPrice(price) {
            const num = Number(price);
            if (isNaN(num)) return '0.00';
            return (num / 100).toFixed(2);
        },
        async goPay() {
            const phone = this.phonenumbers.trim();
            // 双重检查防止重复提交
            if (this.paymentLock) return;
            if (this.paymentLoading) return;

            this.paymentLock = true;
            this.paymentLoading = true;
            try {
                Toast.loading({
                    message: '支付处理中...',
                    forbidClick: true,
                    duration: 0
                });
                if (this.totalPay == 0) {
                    const prepayRes = await plantAPI.conversionOrder({
                        rechargeNumber: phone,
                        cardIds: this.selectedCards,
                        additionalAmount: this.showPrice,
                        seatDeductions: this.seatDeductions,
                        productNo: this.info.product_no
                    });
                    if (prepayRes.code == 200) {
                        Toast.success('兑换成功');
                        this.show = false;
                        this.$router.push({
                            path: '/welfare'
                        })
                    } else {
                        Toast.fail(prepayRes.message);
                    }
                } else if (this.totalPay > 0) {
                    const paymentRes = await plantAPI.prepaymentShop({
                        consumeAmount: this.showPrice,
                        description: this.info.use_explain,
                        productNo: this.info.product_no,
                        rechargeNumber: phone,
                        seatDeductions: this.seatDeductions,
                        totalFee: this.totalPay,
                        tradeType: 2,
                        wxOpenId: localStorage.getItem("openId") // 优先使用 localStorage
                        // wxOpenId: localStorage.getItem("openId")
                    });
                    this.paramsData = paymentRes.data;
                    this.show = false;
                    await this.handlePay();
                }
            } catch (error) {
                console.log(error)
                Toast.fail('支付失败，请重试');
            } finally {
                this.paymentLoading = false;
                // 延迟解锁，防止快速连续点击
                setTimeout(() => {
                    this.paymentLock = false;
                }, 1000);
                Toast.clear();

            }
        },
        async handlePay() {
            try {
                const paySuccess = await wechatPay.pay({
                    package: this.paramsData.packageVal,
                    appId: this.paramsData.appId,
                    nonceStr: this.paramsData.nonceStr,
                    paySign: this.paramsData.paySign,
                    signType: this.paramsData.signType,
                    timeStamp: this.paramsData.timeStamp,
                });

                if (paySuccess) {
                    Toast.success('兑换成功');
                    setTimeout(() => {
                        this.$router.push({
                            path: '/welfare'
                        });
                    }, 1000)
                }
            } catch (error) {
            }
        },
        isCardSelected(id) {
            return this.selectedCards.includes(id);
        },
        // selectPayment(type, cardMode, item) {
        //     if (this.selectedCardMode && this.selectedCardMode !== cardMode) {
        //         this.$toast(`请勿选择不同类型的卡`);
        //         return;
        //     }
        //     const index = this.selectedCards.indexOf(item.id);

        //     if (cardMode == 1) {
        //         if (index === -1) {
        //             this.selectedCards = [item.id];
        //             this.selectedCardMode = cardMode;
        //         } else {
        //             this.selectedCards = [];
        //             this.selectedCardMode = null;
        //         }
        //     } else {
        //         if (index === -1) {
        //             if (this.hasEnoughPointsCard) {
        //                 this.$toast('当前积分卡已足够支付，无需选择更多');
        //                 return;
        //             }
        //             this.selectedCards.push(item.id);
        //             this.selectedCardMode = cardMode;
        //             const selectedCard = this.cardList.find(c => c.id === item.id);
        //             if (selectedCard && selectedCard.balance >= this.info.official_price) {
        //                 this.hasEnoughPointsCard = true;
        //             }
        //         } else {
        //             this.selectedCards.splice(index, 1);
        //             if (this.selectedCards.length === 0) {
        //                 this.selectedCardMode = null;
        //                 this.hasEnoughPointsCard = false;
        //             } else {
        //                 const total = this.selectedCards.reduce((sum, id) => {
        //                     const card = this.cardList.find(c => c.id === id);
        //                     return sum + (card ? card.balance : 0);
        //                 }, 0);
        //                 this.hasEnoughPointsCard = total >= this.info.official_price;
        //             }
        //         }
        //     }
        // },


        selectPayment(type, cardMode, item) {
            // 如果已经选择了卡且类型不同，提示用户
            if (this.selectedCardMode && this.selectedCardMode !== cardMode) {
                this.$toast(`请勿选择不同类型的卡`);
                return;
            }

            // 检查是否已经选择了当前卡
            const index = this.selectedCards.indexOf(item.id);

            if (index === -1) {
                // 如果没选择，清空之前的选择，选择当前卡
                this.selectedCards = [item.id];
                this.selectedCardMode = cardMode;

                // 如果是积分卡，检查是否足够支付
                if (cardMode === 2) {
                    const selectedCard = this.cardList.find(c => c.id === item.id);
                    this.hasEnoughPointsCard = selectedCard && selectedCard.balance >= this.originalPrice;
                }
            } else {
                // 如果已经选择了当前卡，取消选择
                this.selectedCards = [];
                this.selectedCardMode = null;
                this.hasEnoughPointsCard = false;
            }
        },
        handleExchange() {
            // 验证手机号
            if (!this.validatePhone()) {
                return;
            }

            // 使用用户输入的手机号
            const phone = this.phonenumbers.trim();
            plantAPI.getAdditionalAmounts({
                additionalAmount: this.showPrice,
                productNo: this.info.product_no,
                rechargeNumber: phone,
                cardIds: this.selectedCards,
            }).then(res => {
                this.totalPay = res.data.totalPay;
                this.seatDeductions = res.data.seatDeductions;
                this.payDetail()
                this.show = true;
            })
        },
        payDetail() {
            console.log(this.seatDeductions)
            this.seatDeductions.forEach(item => {

                if (this.info.product_no == item.productNo) {
                    item.product_name = this.info.product_name
                }
            });
        },
    }
}
</script>

<style lang="scss" scoped>
.pay-btn {
    &.loading {
        opacity: 0.7;
        pointer-events: none;
    }
}

.head {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    position: relative; // 关键：设置相对定位
    background-color: #ffffff;

    .head-back-img {
        width: 20px;
        height: 20px;
        position: absolute;
        left: 15px;
    }

    .title {
        width: 100%;
        text-align: center;
        font-size: 16px;
        color: #000000;
    }
}

.exchange-container {
    padding-bottom: 80px;
    font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

/* 优化后的商品头部样式 */
.product-header {
    display: flex;
    padding: 16px;
    background: #fff;
    margin: 10px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    align-items: center;
}

.product-image-wrapper {
    position: relative;
    width: 100px;
    height: 100px;
    flex-shrink: 0;
    margin-right: 16px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    .product-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
    }

    .price-badge {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: linear-gradient(transparent, rgba(238, 71, 59, 0.9));
        color: white;
        padding: 4px 0;
        text-align: center;
        font-size: 16px;
        font-weight: bold;
    }
}

.product-info {
    flex: 1;

    .product-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin: 0 0 8px 0;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }

    .product-tag {
        margin-top: 8px;

        span {
            display: inline-block;
            padding: 2px 8px;
            background: #ffeeed;
            color: #ee473b;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
    }
}

/* 充值号码部分样式 */
.recharge-section {
    background: #fff;
    padding: 16px;
    margin: 10px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .recharge-title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 12px;
    }

    .recharge-input {
        background: #f7f8fa;
        border-radius: 8px;
        padding: 12px 16px;

        ::v-deep .van-field__control {
            font-size: 15px;
        }
    }

    .error-tip {
        color: #ee473b;
        font-size: 12px;
        margin-top: 8px;
        text-align: left;
        padding-left: 4px;
    }
}

.payment-cards {
    background: #fff;
    padding: 0 16px;
    border-radius: 8px;
    margin: 0 10px 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .card-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 0;
        border-bottom: 1px solid #f5f5f5;
        cursor: pointer;
        position: relative;

        &:last-child {
            border-bottom: none;
        }

        &.disabled-card {
            opacity: 0.6;
            cursor: not-allowed;

            .card-content {
                pointer-events: none;
            }

            .disabled-tag {
                position: absolute;
                top: 10px;
                right: 80px;
                background-color: #ee473b;
                color: white;
                padding: 2px 8px;
                border-radius: 10px;
                font-size: 12px;
                font-weight: bold;
                z-index: 1;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
                transform: translateY(-50%);
            }
        }

        .card-content {
            display: flex;
            align-items: center;
            flex: 1;

            .card-icon {
                &.movie-card {
                    color: #ee473b;
                }

                &.points-card {
                    color: #ff976a;
                }
            }

            .card-details {
                margin-left: 12px;
                flex: 1;

                .card-number {
                    font-size: 12px;
                    color: #000;
                    margin: 4px 0;
                    // word-break: break-all; /* 长卡号自动换行 */
                }

                .card-title {
                    display: flex;
                    justify-content: space-between;
                    margin: 4px 0;

                    span:first-child {
                        font-size: 16px;
                        color: #323233;
                        font-weight: 500;
                    }

                    .card-balance {
                        font-size: 14px;
                        color: #ee473b;
                        font-weight: 500;
                    }
                }

                .card-expiry {
                    font-size: 12px;
                    color: #969799;
                }
            }
        }

        .van-checkbox {
            margin-left: 10px;
        }
    }
}

.use-explain {
    background: #fff;
    padding: 16px;
    font-size: 14px;
    color: #646566;
    line-height: 1.6;
    border-radius: 8px;
    margin: 0 10px 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    ::v-deep p {
        margin: 0 0 10px 0;
    }
}

.exchange-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

    .exchange-btn {
        height: 44px;
        font-size: 16px;
        font-weight: 500;
        background: linear-gradient(94deg, #ee473b 0%, #f6766d 58%, #ee473b 100%);
        border: none;
    }
}

.dialog_data {
    width: 100%;
    height: 100%;
    color: #666;
    font-size: 14px;
    background: #fafafa;
    text-align: center;
    padding: 18px 12px;
    box-sizing: border-box;

    .detailList {
        width: 100%;
        margin: auto;
        background: #fff;
        border-radius: 6px;
        margin-top: 10px;
        padding: 10px 20px;
        box-sizing: border-box;
        padding-bottom: 10px;

        >div {
            margin-top: 5px;
            width: 100%;
            text-align: left;
            font-size: 14px;
            font-weight: bold;
        }

        .flex_data-money:nth-child(1) {
            >div:nth-child(2) {
                display: flex;
                align-items: center;

                ::v-deep .van-icon {
                    color: #666666;
                }

                >span:nth-child(1) {
                    margin: 0 1px 0 0;
                    font-size: 14px;
                    font-weight: bold;
                }

                >span:nth-child(2) {
                    font-size: 18px;
                    font-weight: bold;
                }
            }
        }

        .flex_data-money:nth-child(2) {
            >div:nth-child(2) {
                display: flex;
                align-items: center;

                >span:nth-child(1) {
                    font-size: 14px;
                    font-weight: bold;
                }

                >span:nth-child(2) {
                    color: rgba(251, 55, 119, 1);
                    font-size: 18px;
                    font-weight: bold;
                    margin-left: 1px;
                }
            }
        }
    }

    .flex-btn {
        width: 100%;
        padding-top: 20px;
        display: flex;
        flex-direction: row-reverse;

        >div {
            margin-left: 18px;
            border-radius: 20px;
            width: 160px;
            height: 40px;
            line-height: 40px;
            text-align: center;
            color: rgba(255, 255, 255, 1);
            font-size: 16px;
            background-color: rgba(251, 55, 119, 1);
        }
    }

    .title {
        width: 70px;
        color: #000;
        font-size: 16px;
        font-weight: bold;
        margin: 0 auto 10px;
        text-align: center;
        display: flex;
        justify-content: space-between;
    }
}
</style>